package com.company.project.service.impl;

import com.company.project.common.utils.BeanCopierUtils;
import com.company.project.vo.req.BasicInformationReq;
import com.company.project.vo.req.MedicalRegistrationReq;
import com.alibaba.fastjson.JSON;
import com.company.project.common.config.HealthConfig;
import com.company.project.common.utils.Constant;
import com.company.project.entity.EJkzGrdjxxEntity;
import com.company.project.entity.EJkzRecordLogEntity;
import com.company.project.service.BasicInformationTaskService;
import com.company.project.service.EJkzGrdjxxService;
import com.company.project.service.EJkzRecordLogService;
import com.company.project.vo.resp.HealthCertificateResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.codec.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author liuhui
 * @Created 2020-11-16
 */
@Service
@Slf4j
public class BasicInformationTaskServiceImpl implements BasicInformationTaskService {
    private static final String BASIC_INFORMATION = "/api/exchange/jbxxRegister";
    private static final String MEDICAL_REGISTRATION = "/api/exchange/djxxRegister";
    @Resource
    private HealthConfig healthConfig;
    @Resource
    private EJkzRecordLogService eJkzRecordLogService;
    @Resource
    private EJkzGrdjxxService eJkzGrdjxxService;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public boolean uploadBasicInformation(EJkzGrdjxxEntity entity) {
        // 1、上传基础信息
        if ((entity.getPhoto() == null || entity.getPhoto().length == 0) && StringUtils.isEmpty(entity.getPhotourl())) {
            log.error("图片数据不存在----！");
            return false;
        }
        BasicInformationReq basicInformationReq = getBasicInformationReq(entity);
        String result = sendMessage(JSON.toJSONString(basicInformationReq), healthConfig.getUrl() + BASIC_INFORMATION);
        HealthCertificateResult healthCertificateResult = JSON.parseObject(result, HealthCertificateResult.class);
        boolean uploadResult = healthCertificateResult.getSuccess();
        // 接口调用失败
        if (!uploadResult) {
            log.info("基础信息调用失败={}", entity);
            return false;
        }
        eJkzRecordLogService.save(buildRecordLogByBasicInfo(entity, result, uploadResult));
        // 2、上传登记信息
        MedicalRegistrationReq medicalRegistrationReq = getMedicalRegistrationReq(entity);
        result = sendMessage(JSON.toJSONString(medicalRegistrationReq), healthConfig.getUrl() + MEDICAL_REGISTRATION);
        healthCertificateResult = JSON.parseObject(result, HealthCertificateResult.class);
        uploadResult = healthCertificateResult.getSuccess();
        entity.setUploadStatus(Constant.DATA_UPLOAD);
        eJkzGrdjxxService.saveOrUpdate(entity);
        eJkzRecordLogService.save(buildRecordLogByMedicalRegistration(entity, result, uploadResult));
        return uploadResult;
    }


    /**
     * 构建基本信息
     */
    private BasicInformationReq getBasicInformationReq(EJkzGrdjxxEntity entity) {
        BasicInformationReq basicInformationReq = BeanCopierUtils.copyForClass(entity, BasicInformationReq.class);
        basicInformationReq.setUsername(healthConfig.getUserName());
        basicInformationReq.setPassword(healthConfig.getPassword());
        basicInformationReq.setBgk_lx(entity.getOperationType());
        basicInformationReq.setBirthday(entity.getBirthday());
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append("data:image/jpeg;base64,");
        stringBuffer.append(Base64.encodeToString(entity.getPhoto()));
        basicInformationReq.setPictureBase64(stringBuffer.toString());
        basicInformationReq.setPictureUrl(entity.getPhotourl());
        basicInformationReq.setTjjgName(entity.getYljgCompName());
        return basicInformationReq;
    }

    /**
     * 构建基本信息日志
     *
     * @param param
     * @param result
     * @param uploadResult
     * @return
     */
    private EJkzRecordLogEntity buildRecordLogByBasicInfo(EJkzGrdjxxEntity param, String result, boolean uploadResult) {
        EJkzRecordLogEntity logEntity = new EJkzRecordLogEntity();
        logEntity.setSclx(Constant.BASIC_INFORMATION_TYPE);
        logEntity.setWbId(param.getWbId());
        logEntity.setUploadStatus(uploadResult ? Constant.UPLOAD_STATUS_SUCCESS : Constant.UPLOAD_STATUS_FAIL);
        logEntity.setUploadResult(result);
        logEntity.setCreateTime(new Date());
        logEntity.setUpdateTime(new Date());
        logEntity.setDelFlag(Constant.DATA_NOT_DELETED_STRING_VALUE);
        return logEntity;
    }

    /**
     * 构建登记信息日志
     *
     * @param entity
     */
    private MedicalRegistrationReq getMedicalRegistrationReq(EJkzGrdjxxEntity entity) {
        MedicalRegistrationReq medicalRegistrationReq = BeanCopierUtils.copyForClass(entity, MedicalRegistrationReq.class);
        medicalRegistrationReq.setUsername(healthConfig.getUserName());
        medicalRegistrationReq.setPassword(healthConfig.getPassword());
        medicalRegistrationReq.setBgk_lx(entity.getOperationType());
        medicalRegistrationReq.setCompName(entity.getCompanyName());
        medicalRegistrationReq.setProfessionType(getProfessionType(entity.getType()));
        medicalRegistrationReq.setHasCompany(0);
        medicalRegistrationReq.setTjjgName(entity.getYljgCompName());
        if (StringUtils.isNotBlank(entity.getCompanyName())) {
            medicalRegistrationReq.setHasCompany(1);
        }
        return medicalRegistrationReq;
    }

    /**
     * 构建体检登记日志
     */
    private EJkzRecordLogEntity buildRecordLogByMedicalRegistration(EJkzGrdjxxEntity param, String result, boolean uploadResult) {
        EJkzRecordLogEntity logEntity = new EJkzRecordLogEntity();
        logEntity.setSclx(Constant.PHYSICAL_EXAMINATIO_TYPE);
        logEntity.setWbId(param.getWbId());
        logEntity.setUploadStatus(uploadResult ? Constant.UPLOAD_STATUS_SUCCESS : Constant.UPLOAD_STATUS_FAIL);
        logEntity.setUploadResult(result);
        logEntity.setCreateTime(new Date());
        logEntity.setUpdateTime(new Date());
        logEntity.setDelFlag(Constant.DATA_NOT_DELETED_STRING_VALUE);
        return logEntity;
    }

    /**
     * 发送消息
     *
     * @param params
     * @param url
     * @return
     */
    private String sendMessage(String params, String url) {
        log.info("上传参数={}", params);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(params, headers);
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForEntity(url, request, String.class).getBody();
        log.info("上传结果={}", result);
        return result;
    }

    private String getProfessionType(String type) {
        if (StringUtils.isEmpty(type)) {
            return "110"; //默认为110
        }
        if (type.equals("01")) {
            return "100";
        }
        if (type.equals("02")) {
            return "101";
        }
        if (type.equals("03")) {
            return "103";
        }
        if (type.equals("99")) {
            return "110";
        }
        return "110";
    }
}
